package com.xhis.homenurse.tools;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;

/**
 * * 通过web请求下载文件
 *
 * @author 张兵
 */
public class DownFileByWebRequest
{
    /**
     * 下载文件
     *
     * @param url      文件地址(url)
     * @param savePath 文件保存地址
     * @throws Exception
     */
    public static void DownFile(String url, String savePath) throws Exception
    {
        if (url == null || url.equals(""))
            throw new Exception("url地址不能为空!");

        if (savePath == null || savePath.equals(""))
            throw new Exception("文件保存路径不能为空!");

        byte[] mbyte = new byte[50000];
        int count = 0;
        URL address;
        HttpURLConnection con = null;
        InputStream reader = null;
        FileOutputStream fos = null;

//		int reTimeout = 0;
        while (true) {
            try {
                address = new URL(url);
                con = (HttpURLConnection) address.openConnection();
                // 设置超时和读取超时；
                con.setConnectTimeout(20000);
                con.setReadTimeout(10000);
                int code = con.getResponseCode();
                String message = con.getResponseMessage();
                // 响应失败；
                if (code != 200) {
                    throw new Exception(message);
                }

                reader = con.getInputStream();
                // 不以追加的方式写入到文件；
                fos = new FileOutputStream(savePath, false);
                while (true) {
                    count = reader.read(mbyte);
                    if (count == -1)
                        break;
                    fos.write(mbyte, 0, count);
                }
                return;
            } catch (SocketTimeoutException ex) {
//				if (reTimeout < 3) {
//					Thread.sleep(1000);
//					reTimeout++;
//					continue;
//				}
                throw ex;
            } finally {
                if (fos != null)
                    fos.close();
                if (reader != null)
                    reader.close();
                if (con != null)
                    con.disconnect();
            }
        }
    }
}
